package com.fzebu.fastboot.form.parser.impl;

import com.alibaba.fastjson.JSONObject;
import com.fzebu.fastboot.annotations.form.Browser;
import com.fzebu.fastboot.form.parser.AbstractTypeParser;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author Jack
 * @version 1.0.0
 * @create 2020/1/26 22:51
 */
public class BrowserTypeParser extends AbstractTypeParser {

    public static final String DEFAULT_SHOW_NAME = "ID";

    public BrowserTypeParser(Field field, String alias, String value) {
        super(field, alias, value);
    }

    @Override
    public Object parse() {
        Browser browser = this.field.getAnnotation(Browser.class);
        boolean multiple = browser.multiple();
        String table = browser.table();
        String showName = browser.showName();
        if (multiple) {
            return handlerMultiple(table, showName);
        }
        if (StringUtils.equalsIgnoreCase(showName, DEFAULT_SHOW_NAME)) {
            return value;
        }
        if (StringUtils.isNotEmpty(table) && StringUtils.isNotEmpty(showName)) {
            String sql = "SELECT ID, "+ showName +" FROM "+ table +" WHERE ID=?";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql, value);
            if (rs.next()) {
                return rs.getString(showName);
            }
        }
        return value;
    }

    private Object handlerMultiple(String table, String showName) {
        Class<?> fieldType = this.field.getType();
        if (!Map.class.isAssignableFrom(fieldType)) {
            return value;
        }
        String sql = "SELECT ID, "+ showName +" FROM " + table + " WHERE id IN ("+ value +")";
        RecordSet rs = new RecordSet();
        rs.execute(sql);
        JSONObject res = new JSONObject(rs.getCounts());
        while (rs.next()) {
            String id = rs.getString(DEFAULT_SHOW_NAME);
            String name = rs.getString(showName);
            res.put(id, name);
        }
        return res.toJavaObject(fieldType);
    }
}
